import { Injectable, UnauthorizedException, BadRequestException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UsersService } from '../users/users.service';
import { RegisterDto } from './dto/register.dto';
import { LoginDto } from './dto/login.dto';
import * as bcrypt from 'bcrypt';
import { EmailService } from '../email/email.service';

/**
 * 认证服务
 */
@Injectable()
export class AuthService {
  private emailCodeStore = new Map<string, { code: string; expires: number }>();

  constructor(
    private usersService: UsersService,
    private jwtService: JwtService,
    private emailService: EmailService,
  ) {
    // 定期清理过期验证码
    setInterval(() => {
      const now = Date.now();
      for (const [key, value] of this.emailCodeStore.entries()) {
        if (value.expires < now) {
          this.emailCodeStore.delete(key);
        }
      }
    }, 60000);
  }

  /**
   * 用户注册
   */
  async register(registerDto: RegisterDto) {
    const { email, password, nickname } = registerDto;

    // 检查邮箱是否已存在
    const existingUser = await this.usersService.findByEmail(email);
    if (existingUser) {
      throw new UnauthorizedException('该邮箱已被注册');
    }

    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);

    // 创建用户
    const user = await this.usersService.create({
      email,
      password: hashedPassword,
      nickname,
    });

    // 生成 JWT
    const token = this.generateToken(user.id, user.email);

    return {
      user: {
        id: user.id,
        email: user.email,
        nickname: user.nickname,
        avatar: user.avatar,
        subscriptionType: user.subscriptionType,
      },
      token,
    };
  }

  /**
   * 用户登录
   */
  async login(loginDto: LoginDto) {
    const { email, password } = loginDto;

    // 查找用户
    const user = await this.usersService.findByEmail(email);
    if (!user) {
      throw new UnauthorizedException('邮箱或密码错误');
    }

    // 验证密码
    const isPasswordValid = await bcrypt.compare(password, user.password);
    if (!isPasswordValid) {
      throw new UnauthorizedException('邮箱或密码错误');
    }

    // 生成 JWT
    const token = this.generateToken(user.id, user.email);

    return {
      user: {
        id: user.id,
        email: user.email,
        nickname: user.nickname,
        avatar: user.avatar,
        subscriptionType: user.subscriptionType,
        subscriptionEndDate: user.subscriptionEndDate,
      },
      token,
    };
  }

  /**
   * 生成 JWT Token
   */
  private generateToken(userId: number, email: string): string {
    const payload = { sub: userId, email };
    return this.jwtService.sign(payload);
  }

  /**
   * 验证用户邮箱和密码（用于本地策略）
   */
  async validateUser(email: string, password: string) {
    const user = await this.usersService.findByEmail(email);
    if (!user) {
      return null;
    }

    const isPasswordValid = await bcrypt.compare(password, user.password);
    if (!isPasswordValid) {
      return null;
    }

    return {
      id: user.id,
      email: user.email,
      nickname: user.nickname,
      avatar: user.avatar,
      subscriptionType: user.subscriptionType,
      subscriptionEndDate: user.subscriptionEndDate,
    };
  }

  /**
   * 验证 Token（用于 JWT 策略）
   */
  async validateUserById(userId: number) {
    return await this.usersService.findOne(userId);
  }

  /**
   * 发送邮箱验证码
   */
  async sendEmailCode(email: string) {
    // 生成6位数字验证码
    const code = Math.floor(100000 + Math.random() * 900000).toString();
    
    // 存储验证码（5分钟过期）
    this.emailCodeStore.set(email, {
      code,
      expires: Date.now() + 5 * 60 * 1000,
    });

    // 发送邮件
    const sent = await this.emailService.sendVerificationCode(email, code);
    
    if (!sent) {
      throw new BadRequestException('邮件发送失败，请稍后重试');
    }

    return { message: '验证码已发送，请查收邮件' };
  }

  /**
   * 邮箱验证码登录
   */
  async loginWithEmailCode(email: string, code: string) {
    const stored = this.emailCodeStore.get(email);

    if (!stored) {
      throw new BadRequestException('验证码已过期或不存在');
    }

    if (stored.expires < Date.now()) {
      this.emailCodeStore.delete(email);
      throw new BadRequestException('验证码已过期');
    }

    if (stored.code !== code) {
      throw new BadRequestException('验证码错误');
    }

    // 验证成功，删除验证码
    this.emailCodeStore.delete(email);

    // 查找或创建用户
    let user = await this.usersService.findByEmail(email);
    
    if (!user) {
      // 如果用户不存在，自动注册
      const hashedPassword = await bcrypt.hash(Math.random().toString(36), 10);
      user = await this.usersService.create({
        email,
        password: hashedPassword,
        nickname: email.split('@')[0],
      });
      
      // 发送欢迎邮件
      await this.emailService.sendWelcomeEmail(email, user.nickname);
    }

    // 生成 JWT
    const token = this.generateToken(user.id, user.email);

    return {
      user: {
        id: user.id,
        email: user.email,
        nickname: user.nickname,
        avatar: user.avatar,
        subscriptionType: user.subscriptionType,
      },
      token,
    };
  }
}





